package com.dsl.tms;

import com.alibaba.druid.pool.DruidDataSource;
import com.dsl.tms.datasource.DataSourceContextHolder;
import com.dsl.tms.datasource.DynamicDataSource;
import com.dsl.tms.entity.tmsdb.DB;
import com.dsl.tms.mapper.tmsdb.DBMapper;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
@EnableDiscoveryClient
@EnableAutoConfiguration
@EnableResourceServer
public class InterfaceClientApplication implements CommandLineRunner {


    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    public static void main(String[] args) {
        SpringApplication.run(InterfaceClientApplication.class, args);
    }

    @Override
    public void run(String... strings) throws Exception {
        //切换至tmsdb数据库
        DataSourceContextHolder.setDBType("tmsdb");
        DB tmsdb = sqlSessionTemplate.getMapper(DBMapper.class).getDBByDbName("tmsdb");
        //重复设置tmsdb数据的datasource
        DruidDataSource tmsDatasource = new DruidDataSource();
        tmsDatasource.setDriverClassName(tmsdb.getDriver_class_name());
        tmsDatasource.setUrl(tmsdb.getUrl());
        tmsDatasource.setUsername(tmsdb.getUsername());
        tmsDatasource.setPassword(tmsdb.getPassword());

        Map<Object,Object> datasourceMap = new HashMap<>();
        datasourceMap.put("tmsdb",tmsDatasource);

        //将所有数据库的信息放入datasourceMap里面
        ArrayList<DB> dbList = sqlSessionTemplate.getMapper(DBMapper.class).getDBList("wms");
        for (DB wmsDBInfo:dbList){
            DruidDataSource wmsDatasource = new DruidDataSource();
            wmsDatasource.setDriverClassName(wmsDBInfo.getDriver_class_name());
            wmsDatasource.setUrl(wmsDBInfo.getUrl());
            wmsDatasource.setUsername(wmsDBInfo.getUsername());
            wmsDatasource.setPassword(wmsDBInfo.getPassword());
            datasourceMap.put(wmsDBInfo.getDbname(),wmsDatasource);
        }

        DynamicDataSource.getInstance().setTargetDataSources(datasourceMap);


    }
}
